package com.zzt.video.task;

import com.zzt.video.model.dto.RankListDto;
import com.zzt.video.service.SeriesService;
import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RBucket;
import org.redisson.api.RedissonClient;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.concurrent.TimeUnit;

@Slf4j
@Component
public class SeriesRankTask {

    @Autowired
    private SeriesService seriesService;

    @Autowired
    private RedissonClient redissonClient;

    /**
     * 每天早上6点执行，生成日排行榜和周排行榜
     */
    @Scheduled(cron = "0 0 0 * * ?")
    public void generateRankings() {
        log.info("开始生成日排行榜和周排行榜");

        try {
            generateDailyRankings();
            generateWeeklyRankings();
            log.info("排行榜生成完成");
        } catch (Exception e) {
            log.error("生成排行榜失败", e);
        }
    }

    /**
     * 生成日排行榜
     */
    private void generateDailyRankings() {
        log.info("开始生成日排行榜");

        // type有四种值：1, 2, 3, 4，5
        for (int type = 1; type <= 5; type++) {
            try {
                // 获取该类型昨日观看次数排行前10的视频
                List<RankListDto> dailyRankList = seriesService.getDailyViewRankByType(type, 10);

                // 存入Redis，key为 series:rank:daily:{type}
                String redisKey = "series:rank:daily:" + type;
                RBucket<List<RankListDto>> rankBucket = redissonClient.getBucket(redisKey); // 保存2天
                rankBucket.set(dailyRankList);
                rankBucket.expire(2, TimeUnit.DAYS);

                log.info("生成type={}的日排行榜成功，共{}条", type, dailyRankList.size());
            } catch (Exception e) {
                log.error("生成type={}的日排行榜失败", type, e);
            }
        }
    }

    /**
     * 生成周排行榜
     */
    private void generateWeeklyRankings() {
        log.info("开始生成周排行榜");

        // type有四种值：1, 2, 3, 4，5
        for (int type = 1; type <= 5; type++) {
            try {
                // 获取该类型本周观看次数排行前10的视频
                List<RankListDto> weeklyRankList = seriesService.getWeeklyViewRankByType(type, 10);

                // 存入Redis，key为 series:rank:weekly:{type}
                String redisKey = "series:rank:weekly:" + type;
                RBucket<List<RankListDto>> rankBucket = redissonClient.getBucket(redisKey); // 保存2天
                rankBucket.set(weeklyRankList);
                rankBucket.expire(8, TimeUnit.DAYS); // 保存8天

                log.info("生成type={}的周排行榜成功，共{}条", type, weeklyRankList.size());
            } catch (Exception e) {
                log.error("生成type={}的周排行榜失败", type, e);
            }
        }
    }
}
